package com.suman.rss.parser;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.suman.bbcticker.R;
import com.suman.rss.FeedItem;
import com.suman.rss.RssFeed;

public class RssFeedHandler extends DefaultHandler {

	// Used to define what elements we are currently in
	private boolean inTitle = false;
	private boolean inLink = false;
	private boolean inDescription = false;
	private boolean inItem = false;

	private RssFeed rssFeed = new RssFeed();
	private FeedItem currentFeedItem;

	@Override
	public void startElement(String uri, String name, String qName, Attributes atts) {

		if (name.trim().equals("title")) {
			inTitle = true;
		} else if (name.trim().equals("description")) {
			inDescription = true;
		} else if (name.trim().equals("link")) {
			inLink = true;
		} else if (name.trim().equals("item")) {
			inItem = true;
			currentFeedItem = new FeedItem();
		}

	}

	@Override
	public void endElement(String uri, String name, String qName) throws SAXException {

		if (name.trim().equals("title")) {
			inTitle = false;
		} else if (name.trim().equals("description")) {
			inDescription = false;
		} else if (name.trim().equals("link")) {
			inLink = true;
		} else if (name.trim().equals("item")) {
			inItem = false;
			rssFeed.addFeedItem(currentFeedItem);
		}

	}

	@Override
	public void characters(char ch[], int start, int length) {

		String chars = (new String(ch).substring(start, start + length));
		if (inItem) {
			if (inTitle) {
				inTitle = false;
				currentFeedItem.setTitle(chars);
			} else if (inLink) {
				inLink = false;
				currentFeedItem.setLink(chars);
			} else if (inDescription) {
				inDescription = false;
				String processDescriptionForAtomFeed = processDescriptionForAtomFeed(chars);
				currentFeedItem.setDescription(processDescriptionForAtomFeed);
			}

		}
	}

	private String processDescriptionForAtomFeed(String description) {
		if (description != null) {
			if (description.contains("</p>")) {
				// This might be an ATOM feed
				String paragraphString = description.substring(description.lastIndexOf("<p"), description
				        .lastIndexOf("</p>"));
				return paragraphString.substring(paragraphString.indexOf(">") + 1);
			}
		}
		return description;
	}

	public RssFeed createFeed(URL url) throws ParserConfigurationException, SAXException, IOException {

		System.setProperty("javax.xml.parsers.SAXParserFactory", "org.ccil.cowan.tagsoup.jaxp.SAXFactoryImpl");

		SAXParserFactory spf = SAXParserFactory.newInstance();
		// System.out.println("Ok, SAX factory JAXP creates is: "+spf);
		// System.out.println("Let's parse...");

		// SAXParserImpl sp = org.ccil.cowan.tagsoup.jaxp.SAXParserImpl.newInstance(null);
		// XMLReader xr = sp.getXMLReader();
		// xr.setContentHandler(this);

		URLConnection conn = url.openConnection();
		conn.setConnectTimeout(R.string.rssfeed_connecttimeout);
		conn.setReadTimeout(R.string.rssfeed_readtimeout);

		InputSource inputSource = new InputSource(conn.getInputStream());
		spf.newSAXParser().parse(inputSource, this);
		// xr.parse(inputSource);

		return rssFeed;
	}

}
